<?php

/*
 * This file is part of ibrand/EC-Open-Server.
 *
 * (c) iBrand <https://www.ibrand.cc>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace iBrand\EC\Open\Server\Http\Controllers;

use App\Libs\Util;
use App\Libs\WeChat\Transfer\WxTransfer;
use EasyWeChat;
use iBrand\Component\Order\Models\Order;
use iBrand\Component\Order\Repositories\OrderRepository;
use iBrand\Component\Payment\Models\Payment;
use Illuminate\Http\Request;
use iBrand\Component\Pay\Facades\Charge;
use Illuminate\Support\Facades\DB;

class WechatPayController extends Controller
{
    private $orderRepository;
    private $mch_id;
    private $key;
    private $appid;





    public function __construct(OrderRepository $orderRepository)
    {
        $this->orderRepository = $orderRepository;
        $this->mch_id = env('AGENT_XCX_MCHID','1509155141');
        $this->key = env('AGENT_XCX_KEY', '2934e7d15453e97507ef794cf7b0519d');
        $this->appid = env('AGENT_XCX_APPID', 'wxe1c8ba21a15f4f3e');
    }


    public function transformer(){
        $rand = md5(time() . mt_rand(0,1000));
        $row = array(
            'nonce_str'=>"$rand",//随机字符串
            'partner_trade_no'=>'11111111111111111',  //商户转账唯一订单号 ------- 必须唯一
            'openid'=>'oyybT5BSwzkX4MUHbcrSTbrCd_Po',//isset($data['account']) && !empty(trim($data['account']))?$data['account']:$user['wx_openid'],//收款方账户。
            'check_name'=>'NO_CHECK',//NO_CHECK：不校验真实姓名FORCE_CHECK：强校验真实姓名
            'amount'=>0.01*100,//企业付款金额，单位为分
            'desc'=>'本宫艺术甜品提现',//	企业付款操作说明信息。必填。
        );
        $wechat = new WxTransfer();
        $WxRes = $wechat->WxTransfer( $row );
        var_dump($WxRes);
    }



    public function refund()
    {
        $order_no = request('order_no');
        if( !isset($order_no) || empty( trim( $order_no ) ) )
        {
            return false;
        }
        if (!$order_no || !$order = $this->orderRepository->getOrderByNo($order_no)) {
            return $this->failed('订单不存在');
        }

        if($order->status!=2){
            return $this->failed('订单状态错误！');
        }


        $wx = new WxTransfer();
        $refund = [];
        $refund['order_no']=$order->order_no;
        $refund['total_fee']=$order->total;
        $res = $wx->refund($refund);

        if($res){
            //修改订单的状态
            DB::table('ibrand_order')->where(['order_no'=>$order->order_no])->update(['status'=>7]);
            return $this->success('退款成功');
        }else{
            return $this->failed('微信退款失败');
        }
        exit;



        $data = array();
        $rand = md5(time() . mt_rand(0,1000));
        $data['appid'] = $this->appid;
        $data['mch_id'] =  $this->mch_id;
        $data['nonce_str'] = "$rand";
        $data['out_trade_no'] = $order->order_no;
        $data['out_refund_no'] = $order->order_no;
        $data['total_fee'] = $order->total;
        $data['refund_fee'] = $order->total;;
        ksort($data);
        $signStr = $this->getWxSign( $data );
        $data["sign"] = strtoupper(MD5($signStr));
        $xml = Util::arrayToXml($data);
        $res = Util::weachatPostPemCurl("https://api.mch.weixin.qq.com/secapi/pay/refund",$xml, 0);
        $res = Util::xmlToArray($res);
//        Storage::disk('test')->append('wechatrefunds.log',json_encode($res , 1));

        if( isset($res['result_code']) && $res['result_code'] == 'SUCCESS' )
        {


        }

        return false;
    }


    private function getWxSign($arr)
    {
        $buff = "";
        foreach ($arr as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        $str = $buff."&key=$this->key";
        return $str;
    }

    public function createCharge()
    {
        try{
            $user = request()->user();
            $order_no = request('order_no');

            if (!$order_no || !$order = $this->orderRepository->getOrderByNo($order_no)) {
                return $this->failed('订单不存在');
            }

            $mch_id = env('AGENT_XCX_MCHID','1509155141');
            $key = env('AGENT_XCX_KEY', '2934e7d15453e97507ef794cf7b0519d');
            $appid = env('AGENT_XCX_APPID', 'wxe1c8ba21a15f4f3e');

            $rand = md5(time() . mt_rand(0,1000));
            $param["appid"] = $appid;
            $param["openid"] = $user->openid;
            $param["mch_id"] = $mch_id;
            $param["nonce_str"] = "$rand";
            $param["attach"] = $order->order_no;
            $param["body"] = "PavoMea艺术甜品";
            $param["out_trade_no"] = $order->order_no; //订单单号
            $param["total_fee"] = $order->total;//支付金额
//            if('oyybT5BSwzkX4MUHbcrSTbrCd_Po' == $openid){
//                $param["total_fee"] = 1;//支付金额
//            }
            $param["spbill_create_ip"] = $_SERVER["REMOTE_ADDR"];
            $param["notify_url"] = "https://".$_SERVER['HTTP_HOST']."/api/wechat/notify";
            $param["trade_type"] = "JSAPI";
            $signStr = 'appid='.$param["appid"]."&attach=".$param['attach']."&body=".$param["body"]."&mch_id=".$param["mch_id"]."&nonce_str=".$param["nonce_str"]."&notify_url=".$param["notify_url"]."&openid=".$param["openid"]."&out_trade_no=".$param["out_trade_no"]."&spbill_create_ip=".$param["spbill_create_ip"]."&total_fee=".$param["total_fee"]."&trade_type=".$param["trade_type"];
            $signStr = $signStr."&key=$key";
            $param["sign"] = strtoupper(MD5($signStr));
            $data = Util::arrayToXml($param);
            $postResult = Util::postCurl("https://api.mch.weixin.qq.com/pay/unifiedorder",$data);
            $postObj = Util::xmlToArray( $postResult );
            $json = json_encode($postObj);
            $msg = $postObj['return_code'];
            //记录日志
            savelog('pay_error', ($postResult).'===='.$json);
            if($msg == "SUCCESS"){
                $result["timestamp"] = (string)time();
                $result["nonceStr"] = $postObj['nonce_str'];  //不加""拿到的是一个json对象
                $result["package"] = "prepay_id=".$postObj['prepay_id'];
                $result["signType"] = "MD5";
                $paySignStr = 'appId='.$param["appid"].'&nonceStr='.$result["nonceStr"].'&package='.$result["package"].'&signType='.$result["signType"].'&timeStamp='.$result["timestamp"];
                $paySignStr = $paySignStr."&key=$key";
                $result["paySign"] = strtoupper(MD5($paySignStr));
                $result['appId'] = $appid;
                fun_respon(1,$result);
            }else{
                fun_respon(0,'支付失败');
            }
        }catch (\Exception $exception){


            fun_respon(0,'支付失败');
        }


        $res = Util::postCurl("https://www.baidu.com");
        var_dump($res);exit;






        /*if ($user->cant('pay', $order)) {
            return $this->failed('无权操作此订单');
        }*/

        if (Order::STATUS_INVALID == $order->status) {
            return $this->failed('无法支付');
        }

        if (0 === $order->getNeedPayAmount()) {
            return $this->failed('无法支付，需支付金额为零');
        }

        $charge = Charge::create(['channel' => 'wx_lite'
            , 'order_no' => $order_no
            , 'amount' => $order->getNeedPayAmount()
            , 'client_ip' => \request()->getClientIp()
            , 'subject' => $order->getSubject()
            , 'body' => $order->getSubject()
            , 'extra' => ['openid' => $user->openid]
        ]);

        $data = compact('charge');
        return $this->success($data['charge']['credential']['wechat']);

        //openid 和 订单编号
        /*$payment = EasyWeChat::payment();

        $data = $payment->order->unify([
            'body' => $order->getSubject(),
            'out_trade_no' => $order_no,
            'total_fee' => $order->getNeedPayAmount(),
            'trade_type' => 'JSAPI',
            'openid' => \request('openid'),
            'notify_url' => url('api/wechat/notify', '', true),
        ]);

        if('FAIL' == $data['return_code']){
            return $this->failed($data['return_msg']);
        }

        //包装成前端直接可以用的参数
        if ('SUCCESS' == $data['return_code'] && 'SUCCESS' == $data['result_code']) {
            $jssdk = $payment->jssdk;
            $charge = $jssdk->sdkConfig($data['prepay_id']); // 返回数组
            $charge['timeStamp'] = $charge['timestamp'];
            return $this->success(compact('charge', 'data'));
        } elseif ('FAIL' == $data['result_code']) {
            return $this->failed($data['err_code_des']);
        }
        return $this->failed('支付未知错误');*/
    }


}
